package com.test.system.admin.quartz;

import com.test.system.admin.dao.ScriptDAO;
import com.test.system.admin.pojo.Script;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 徒有琴
 */
@Component
public class MySqlDumpJob implements Job {
    private static ScriptDAO scriptDAO;

    @Autowired
    public void setScriptDAO(ScriptDAO scriptDAO) {
        MySqlDumpJob.scriptDAO = scriptDAO;
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Script script = new Script();
        try {
            String database = "1901";
            String username = "root";
            String password = "";
            String command = "cmd /c \"D:\\Program Files (x86)\\MySQL\\MySQL Server 5.6\\bin\\mysqldump\" -u" + username + " --set-charset=utf8 " + database;
            Process process = Runtime.getRuntime().exec(command);
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf8");
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line + "\r\n");
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm");
            File file = new File("d:/upload/" + format.format(new Date()) + ".sql");
            FileOutputStream outputStream = new FileOutputStream(file);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "utf8");
            outputStreamWriter.write(builder.toString());
            outputStreamWriter.flush();
            outputStreamWriter.close();
            outputStream.close();
            reader.close();
            inputStreamReader.close();
            inputStream.close();
            script.setResult("执行成功");
        } catch (IOException e) {
            e.printStackTrace();
            script.setResult(e.getMessage());
        } finally {
            script.setName("com.test.system.admin.quartz.MySqlDumpJob");
            scriptDAO.updateTime(script);
        }

    }
}
